<?php

namespace app\index\service;

use app\admin\service\LawyerDraftCheckService;
use app\common\model\Area;
use app\common\model\Member;
use app\common\model\MemberDraft;
use app\index\dao\MemberDraftDao;
use app\index\model\UM as UM;
use app\index\traits\CaptchaTrait;
use ShidianUtil\Concurrent\Synchronizer;
use think\exception\ValidateException;

/**
 * Class MemberDraftService
 * @package app\index\service
 */
class MemberDraftService
{
    use CaptchaTrait;

    // dao
    private MemberDraftDao $memberDraftDao;
    private Synchronizer $synchronizer;

    public function __construct(MemberDraftDao $memberDraftDao, Synchronizer $synchronizer)
    {
        $this->memberDraftDao = $memberDraftDao;
        $this->synchronizer = $synchronizer;
    }

    /**
     * 律师入驻
     * @param UM $user
     * @param array $params
     * @return  MemberDraft
     */
    public function addForLawyer(UM $user, array $params): MemberDraft
    {
        $memberId = $user->id;
        $params['headImgUrl'] ??= '/defaultavatar/default_lawyer.png';
        $params['cropImgUrl'] ??= '';
        $params['categories'] ??= [];
        $params['subType'] = '0';

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        if ($user->type != 0 && $user->type != 1) {
            throw new ValidateException('您不能申请成为律师');
        }

        $this->checkCity($params);

        if (empty($params['categories'])) {
            throw new ValidateException('请选择擅长领域');
        }

        //2分钟内只能提交一次
        $record = MemberDraft::where('memberId', $memberId)
            ->where('created', '>=', time() - 120)
            ->find();

        if ($record) {
            throw new ValidateException('您的申请正在审核中，请勿重复提交');
        }

        $params['pf'] = $pf;
        $params['chain'] = $chain;
        $params['promotionGroupId'] = $promotionGroupId;

        return $this->saveMemberDraft($user, $params);
    }

    /**
     * 法务入驻
     * @param UM $user
     * @param array $params
     * @return  MemberDraft
     */
    public function addForLegal(UM $user, array $params): MemberDraft
    {
        $memberId = $user->id;
        $params['headImgUrl'] ??= '/defaultavatar/default_lawyer.png';
        $params['cropImgUrl'] ??= '';
        $params['categories'] ??= [];
        $params['subType'] = '1';

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        if ($user->type != 0 && $user->type != 1) {
            throw new ValidateException('您不能申请成为律师');
        }

        $this->checkCity($params);

        //2分钟内只能提交一次
        $record = MemberDraft::where('memberId', $memberId)
            ->where('created', '>=', time() - 120)
            ->find();

        if ($record) {
            throw new ValidateException('您的申请正在审核中，请勿重复提交');
        }

        $params['pf'] = $pf;
        $params['chain'] = $chain;
        $params['promotionGroupId'] = $promotionGroupId;

        return $this->saveMemberDraft($user, $params);
    }

    /**
     * 插入数据
     * @param Member $member
     * @param array $params
     * @return MemberDraft|null
     */
    public function saveMemberDraft(Member $member, array $params): ?MemberDraft
    {
        $memberId = $member->id;

        if (!is_id($params['provinceId'] ?? null) && is_id($params['cityId'] ?? null)) {
            $city = Area::where('id', $params['cityId'])
                ->where('province', '<>', '0')
                ->where('city', '0')
                ->find();
            if ($city) {
                $params['provinceId'] = $city->province;
            }
        }

        $success = false;
        $record = null;

        $signature = __CLASS__ . $memberId;
        $this->synchronizer->synchronized($signature, function () use (&$success, &$record, $memberId, $params) {

            $data = [
                'memberId' => $memberId,
                'subType' => $params['subType'] ?? '0',
                'realname' => $params['realname'],
                'provinceId' => $params['provinceId'] ?? '0',
                'cityId' => $params['cityId'] ?? '0',
                'practiceNumber' => $params['practiceNumber'] ?? '',
                'practicingLawFirm' => $params['practicingLawFirm'] ?? '',
                'certificatePic' => $params['certificatePic'] ?? '',
                'practiceTime' => $params['practiceTime'] ?? 0,
                'headImgUrl' => $params['headImgUrl'] ?? '',
                'cropImgUrl' => $params['cropImgUrl'] ?? '',
                'idcardPic' => $params['idcardPic'] ?? '',
                'idcard2Pic' => $params['idcard2Pic'] ?? '',
                'idcard' => $params['idcard'] ?? '',
                'legalCompany' => $params['legalCompany'] ?? '',
                'pf' => $params['pf'] ?? '',
                'chain' => $params['chain'] ?? '',
                'promotionGroupId' => $params['promotionGroupId'] ?? '0',
            ];

            $record = $this->memberDraftDao->insertActive($data, []);

            $categoriesIds = ids($params['categories'] ?? []);
            if (!empty($categoriesIds)) {
                $record->categories()->attach($categoriesIds);
            }

            $success = true;
        });

        Member::where('id', $memberId)->data(['isSettled' => 1])->save();

        // 设置定制推送
        if ($success && is_id($params['cityId'] ?? null)) {
            $this->getLawyerDraftCheckService()->saveCustomPush($memberId, $params['cityId']);
        }

        return $record;
    }

    private function getLawyerDraftCheckService(): LawyerDraftCheckService
    {
        return app(LawyerDraftCheckService::class);
    }

    /**
     * @param array $params
     * @return void
     */
    private function checkCity(array &$params): void
    {
        if (!is_id($params['cityId'])) {
            throw new ValidateException('请选择一个城市');
        }

        $city = Area::where('id', $params['cityId'])
            ->where('province', '<>', '0')
            ->where('city', '0')
            ->find();
        if (!$city) {
            throw new ValidateException('请选择正确的城市');
        }
        $params['provinceId'] = $city->province;
    }

}
